package ps.server.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import ps.server.ServerPacketHandler;


public class PsServerSocket extends Thread {
    
    public static final int DEF_SERVER_PORT = 53729;
//    public static final int DEF_SERVER_PORT = 53730;
    
    boolean running = true;
    
    ServerSocket serverSocket;
    
    ServerPacketHandler serverPacketHandler;
    
    public PsServerSocket(ServerPacketHandler serverPacketHandler) {
        super("PsServerSocket");
        this.serverPacketHandler = serverPacketHandler;
    }
    
    public void open(int port) throws IOException {
        serverSocket = new ServerSocket();
        serverSocket.setPerformancePreferences(0, 1, 0);
//        serverSocket.setPerformancePreferences(0, 0, 1);
        
        serverSocket.bind(new InetSocketAddress(port));
        
        start();
    }
    
    public void close() {
        running = false;
        try {
            serverSocket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    @Override
    public void run() {
        while (running) {
            try {
                Socket socket = serverSocket.accept();
                socket.setTcpNoDelay(true);
                
                System.out.println("Connection accepted from: " + socket);
                
                ClientInfo clientInfo = new ClientInfo(socket, serverPacketHandler);
                clientInfo.open();
                
                serverPacketHandler.getClientManager().addClient(clientInfo);
                
                sleep(200);
            } catch (Exception ex) {
                if (running) {
                    ex.printStackTrace();
                }
            } catch (OutOfMemoryError error) {
                System.out.println("OUT OF MEMORY: " + error.getMessage());
                System.gc();
                try {
                    sleep(5000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }                
            }
        }
    }

}
